package org.example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Test2 {
    //leetcode 全排列II https://leetcode.cn/problems/permutations-ii/
    public List<List<Integer>> ret;
    public List<Integer> path;
    public boolean[] vis;
    public List<List<Integer>> permuteUnique(int[] nums) {
        ret = new ArrayList<>();
        path = new ArrayList<>();
        vis = new boolean[21];
        Arrays.sort(nums);
        backtracking(nums);
        return ret;
    }

    public void backtracking(int[] nums) {
        if (path.size() == nums.length) {
            ret.add(new ArrayList<>(path));
        }
        for (int i = 0; i < nums.length; i++) {
            if (!vis[i] && (i == 0 || nums[i-1] != nums[i] || vis[i - 1])) {
                path.add(nums[i]);
                vis[i] = true;
                backtracking(nums);
                path.remove(path.size() - 1);
                vis[i] = false;
            }
        }
    }
}
